import Vue from 'vue'
import Storage from 'lib/storage'
import addressService from './address'

const DEFAULT_ADDRESS_KEY = 'DEFAULT_ADDRESS_KEY'

export default {
    fetch: (order_id) => Vue.http.get('get_order', { order_id }),
    delete: (order_id) => Vue.http.post('delete_order', { order_id }),
    fetchs: (offset, state, querys) => Vue.http.get('get_orders', {offset, state, querys }),
    fetchTemp: (cart_ids, product) => Vue.http.get('get_temp_order', { cart_ids, product }),
    create: (cart_ids, product, address_id, shipping_date, message) =>
        Vue.http.post('create_order', { cart_ids, product, address_id, shipping_date, message }),

    canPay (amount, type) {
        if (type !== 'integral') return Promise.resolve('ok')

        return Vue.http.get('test_can_pay', { amount });
    },

    setDefaultAddress (address) {
        Storage.set(DEFAULT_ADDRESS_KEY, {value: address, date: +new Date()});
    },

    getDefaultAddress () {
        let res = Storage.get(DEFAULT_ADDRESS_KEY);
        if (res && res.date + 60 * 60 * 100 > +new Date()) return Promise.resolve({data: res.value});

        return addressService.fetchDefault();
    },
}
